package com.tabjin.rfidsocket.netty;

import com.tabjin.rfidsocket.service.access.ArchCardService;
import com.tabjin.rfidsocket.service.access.impl.ArchCardServiceImpl;
import com.tabjin.rfidsocket.utils.SpringUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.Arrays;

/**
 * @author tabjin
 * create at 2020/11/12 22:41
 * @program rfid_socket
 * @description
 */
public class HandlerRFID extends ChannelInboundHandlerAdapter {

    final static Logger logger = LoggerFactory.getLogger(HandlerRFID.class);

//    @Autowired
//    private ArchCardService archCardService;

    @Value("${rfid.pingpong}")
    private String pingPong;

    public static ChannelGroup users = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 获取客户端传过来的消息
        ByteBuf in = (ByteBuf) msg;

        String srcInfo = ByteBufUtil.hexDump(in).toUpperCase();// 原始报文
        logger.info("收到客户端发来的原始报文：" + srcInfo);
        if (srcInfo == pingPong) {
            logger.info("收到客户端发来的原始心跳报文：" + srcInfo);
        } else if (srcInfo.length() < 20 || srcInfo.length() > 50) {
            logger.info("这边包含命令反馈和其他{}", srcInfo);
        } else {
            ArchCardService archCardService = (ArchCardService) SpringUtil.getBean(ArchCardServiceImpl.class);
            String cardCode = srcInfo.substring(20, 44);
            if (archCardService.hasCardByCardCode(cardCode)) {// 卡号存在
                logger.info("卡号存在{}", cardCode);
                byte header = 0x1B;
                byte command = 0x07;
                byte sequence = 0x00;
                byte opcode = 0x00;
                byte lenLow = 0x03;
                byte lenHigh = 0x00;
                byte data0 = 0x01;
                byte data1 = 0x01;
                byte data2 = 0x01;
                byte checkBCC = 0x01;

                byte[] b = {header, command, sequence, opcode, lenLow, lenHigh, data0, data1, data2, checkBCC};
                ctx.writeAndFlush(Unpooled.copiedBuffer(b));
//                logger.info("PC -> device!!!!!!!!!!!!!!!!!!!!!!! {}", srcInfo.substring(20, 44));
//                logger.info("PC -> device？？？？？？？？{}", Arrays.toString(b));
            } else {
                logger.error("无效卡号{}", cardCode);
            }
        }

        // TODO 将获取到的报文与数据库中的数据进行比对，获取去redis中进行比对
        // 卡片中写入用户id
//        ArchCard archCard = archCardService.getCardByCardId(1);

        // 报文解析
//        int header = in.readMedium();
//        int device = in.readByte();
//        int contentLen = in.readUnsignedShort();
//        ByteBuf bufContent = in.readBytes(contentLen);
//        String Content = bufContent.toString(CharsetUtil.UTF_8);
//
//        System.out.println("header：" + header + "\n" + "device：" + device + "\n" + "Content：" + Content);
//        logger.info("header：" + header + "\n" + "device：" + device + "\n" + "Content：" + Content);


        // 写入并发送信息到远端（客户
//        logger.info("你好，我是服务端，我已经接收到你发送的消息，这是服务端在Read方法中反馈的消息");
//        logger.info("收到客户端发来的消息：" + in.toString(CharsetUtil.UTF_8));
//        ctx.writeAndFlush(Unpooled.copiedBuffer("你好，我是服务端，我已经接收到你发送的消息，这是服务端在Read方法中反馈的消息", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
//        ctx.close();
//        users.remove(ctx.channel());
        logger.error("有异常");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        logger.info("客户端：" + incoming.remoteAddress() + "已连接上来");
        users.add(incoming);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel incoming = ctx.channel();
        logger.info("客户端：" + incoming.remoteAddress() + "已断开");
        users.remove(incoming);
    }
}
